package com.djhu.freepartner.web.control;

import com.djhu.freepartner.bean.PartnerUser;
import com.djhu.freepartner.core.RestRsp;
import com.djhu.freepartner.core.Status;
import com.djhu.freepartner.core.exception.ServiceException;
import com.djhu.freepartner.service.IPartnerUserService;
import com.djhu.freepartner.web.service.session.ISessionService;
import com.djhu.freepartner.web.support.BaseControl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Api("忘记密码api")
@RestController
public class ForgetPassWordControl extends BaseControl {

    private static Logger logger = LoggerFactory.getLogger(ForgetPassWordControl.class.getName());

    @Autowired
    private IPartnerUserService iPartnerUserService;

    @Autowired
    private ISessionService sessionService;

    @ApiOperation(value="忘记密码", notes="忘记密码 找回密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userid", value = "用户登录名", required = true, dataType = "String")
    })
    @PostMapping(value="/user/forgetpass")
    public RestRsp forgetpass(@RequestParam(value = "userid") String userid,@RequestParam(value = "userid") String oldpassword,@RequestParam(value = "userid") String newpassword) throws ServiceException {
        PartnerUser partnerUser = iPartnerUserService.selectById(userid);
        if (partnerUser == null){
            RestRsp restRsp = new RestRsp();
            restRsp.setMsg("用户不存在");
            restRsp.setCode(2);
            return restRsp;
        }
        String password = oldpassword;
        if (!DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(password.getBytes()).getBytes()).equals(partnerUser.getPassword())){
            throw new ServiceException("密码错误",Status.BAD_PARAM.getCode());
        }
        partnerUser.setPassword(newpassword);

        RestRsp restRsp = new RestRsp();
        if (iPartnerUserService.updateById(partnerUser)){

            // 需要删除 登陆状态
            sessionService.deleteSession(partnerUser);
            restRsp.setCode(Status.SUCCESS.getCode());
            return restRsp;
        }else {
            restRsp.setCode(Status.SERVER_ERROR.getCode());
            restRsp.setMsg("密码修改失败 稍后再试");
            return restRsp;
        }
    }

}
